package com.yuan.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author yuanxingke
 * @date 2022/8/1 10:40
 */
@RestController
@Slf4j
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * @param file 注意：此方法的MultipartFile的形参名必须和网页上的名称保持一致
     * @return 返回R
     * @throws IOException 异常
     */
    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());

        //创建一个目录对象
        File dir = new File(basePath);

        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在则创建
            dir.mkdirs();
        }

        //原始文件名字
        String originalFilename = file.getOriginalFilename();
        //原始文件后缀名字
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名字，防止文件名称重复 造成文件覆盖
        String newFileName = UUID.randomUUID().toString() + suffix;

        //将临时文件储存到指定的位置
        file.transferTo(new File(basePath + newFileName));

        return R.success(newFileName);
    }

    /**
     * 下载
     * @param name
     * @param response
     * @throws Exception
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(basePath+name);

        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(fileInputStream,outputStream);
    }



}
